var util = require('../../libs/util.js');
var app = getApp();
Page({
  data: {
    dataList: [],
    searchShowed: false,
    searchVal: "",
    selected: false,
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onLoad: function (e) {
    let that = this
    wx.setNavigationBarTitle({
      "title": app.appName + "--选择车辆"
    });
    if (e.id) {
      this.setData({
        id: e.id
      })
    }
    if (e.tags) {
      this.setData({
        tags: (e.tags == true && e.tags != 'null' && e.tags != 'undefined') ? e.tags : '',
        tagsList: (e.tags == true && e.tags != 'null' && e.tags != 'undefined') ? String(e.tags).split(",") : []
      })
    }
    wx.showToast({
      title: "页面加载中\n请稍候...",
      icon: "loading",
      duration: 5000
    });
    if (this.data?.vehicleLengthList?.length > 0) {
      this.loadVehicleData();
    } else {
      this.loadVehicleProp(function () {
        that.loadVehicleData();
      })
    }
  },
  onReady: function () {
    wx.hideToast()
  },
  showSearch: function () {
    this.setData({
      searchShowed: true
    });
  },
  hideSearch: function () {
    this.setData({
      searchVal: "",
      searchShowed: false
    });
    this.loadVehicleData();
  },
  clearSearch: function () {
    this.setData({
      searchVal: ""
    });
    this.loadVehicleData();
  },
  searchTyping: function (e) {
    this.setData({
      searchVal: e.detail.value
    });
    this.loadVehicleData();
  },
  loadVehicleProp: function (callback) {
    var that = this;
    util.postData("/zhc/datalist/getDataByListId", {
      "list_id": "210D0D4D-3C06-4D71-8635-963B316EC7C5",
      "page": {
        "size": 1000,
        "current": 1,
        "orders": [{
          "column": "a.ADD_TIME",
          "asc": "false"
        }]
      },
      "data": {
        "field": ""
      },
      "repeat_field": [],
      "condition": " a.CO_ID='" + app.globalData.CO_ID + "' and  a.BE_DEL=0  ",
      "virtual_field": []
    }, function (res, error) {
      wx.hideLoading();
      let vehiclePropData = []
      if (res.data.success && res.data?.result?.records.length > 0) {
        vehiclePropData = res.data.result.records
      }
      var vehicleLengthList = {
          name: {},
          code: {}
        },
        vehicleFunctionList = {
          name: {},
          code: {}
        },
        vehicleSourceList = {
          name: {},
          code: {}
        };
      for (var i = 0; i < vehiclePropData.length; i++) {
        if (vehiclePropData[i].type == 'function') {
          vehicleFunctionList.name[vehiclePropData[i].code] = vehiclePropData[i].name
          vehicleFunctionList.code[vehiclePropData[i].name] = vehiclePropData[i].code
        }
        if (vehiclePropData[i].type == 'length') {
          vehicleLengthList.name[vehiclePropData[i].code] = vehiclePropData[i].name
          vehicleLengthList.code[vehiclePropData[i].name] = vehiclePropData[i].code
        }
        if (vehiclePropData[i].type == 'source') {
          vehicleSourceList.name[vehiclePropData[i].code] = vehiclePropData[i].name
          vehicleSourceList.code[vehiclePropData[i].name] = vehiclePropData[i].code
        }
      }
      that.setData({
        vehicleLengthList: vehicleLengthList,
        vehicleFunctionList: vehicleFunctionList,
        vehicleSourceList: vehicleSourceList
      });
      if (callback) {
        callback()
      }
    })
  },
  loadVehicleData() {
    wx.showLoading({
      title: '加载数据中...',
    });
    var that = this;

    let condition = ''
    if (that.data.searchVal) {
      condition = "and ( plate like '%" + that.data.searchVal + "%')"
    }
    util.postData("/zhc/datalist/getDataByListId", {
      "list_id": "F905AEC8-5754-4B14-83E2-672E45717039",
      "page": {
        "size": that.data.pageSize,
        "current": that.data.page,
        "orders": [{
          "column": "a.ADD_TIME",
          "asc": "false"
        }]
      },
      "data": {
        "field":"a.plate,a.driver,a.model,a.coord,a.district,a.total_oil,a.ADD_TIME,a.loadage,a.score,a.vehicle_register,a.vehicle_function,a.INSURANCE,a.tags,a.miles,a.plate_owner,a.temperature_current,a.oils,a.vehicle_size_out,a.vip,a.semitrailer_plate,a.loan_body,a.brand,a.loan_nper,a.province,a.latitude_current,a.iot_box,a.color,a.vehicleVolume,a.address,a.level,a.driver2,a.capacity_company,a.vip_to,a.is_work,a.photo,a.state,a.loan_month,a.ID,a.engineno,a.ischeck,a.buy_date,a.income_ratio,a.roadTC,a.longitude_current,a.cost,a.changeCompany,a.CO_ID,a.loan_first,a.carrier,a.station_address,a.last_keep_date,a.vin,a.approved_load,a.depreciation_ratio,a.truck_type,a.total_weight,a.vehicle_owner,a.img_vehicle_licence,a.mobile_warehouse,a.vehicleSizeWidth,a.vehicleSizeHeight,a.vehicleFunction,a.vehicleLength,a.vehicleSizeLength,a.plate_color,a.img_vehicle,a.station_coord,a.xyp_vehicle,a.operating_permit,a.contract,a.capacity_shipper,a.user_id,a.NO,a.depreciation_month_price,a.vehicle_spec_in,a.semitrailer,a.vehicleSource,a.tp_alarm,a.purchase_date,a.vehicle_key,a.max_speed,a.ADD_USER,a.purchase_price,a.is_oil,a.street,a.app_gps_first,a.vehicle_type,a.city,a.oldId,a.humidity_current,a.BE_DEL"
      },
      "repeat_field": [],
      "condition": " a.CO_ID='" + app.globalData.CO_ID + "' and  a.BE_DEL=0  " + condition,
      "virtual_field": [{
          "relate": "LEFT JOIN",
          "res": "88e65a5ccd734a35a0cac74c9d58ff2e",
          "alias": "b",
          "on": "a.driver=b.ID",
          "type": "",
          "condition": "",
          "from_field": "name",
          "field_name": "name",
          "field_alias": "司机"
        },
        {
          "relate": "LEFT JOIN",
          "res": "88e65a5ccd734a35a0cac74c9d58ff2e",
          "alias": "c",
          "on": "a.driver2=c.ID",
          "type": "",
          "condition": "",
          "from_field": "name",
          "field_name": "name2",
          "field_alias": "副司机"
        }
      ]
    }, function (res, error) {
      if (res.data.success && res.data?.result?.records.length > 0) {
        var _data = res.data.result.records,
          _data_ = [];

        for (var i = 0; i < _data.length; i++) {
          var item = _data[i];
          item.vehicleLengthName = that.data.vehicleLengthList.name[item.vehicleLength];
          item.vehicleSourceName = that.data.vehicleSourceList.name[item.vehicleSource];
          item.vehicleFunctionName = that.data.vehicleFunctionList.name[item.vehicleFunction];
          item.CO_NAME = (_data[i].CO_ID == app.globalData.CO_ID ? '自有车辆' : _data[i].CO_NAME) || '个人（自由）车辆';
          _data_.push(item);
        };
        that.setData({
          dataList: _data_
        });

      } else {
        that.setData({
          dataList: []
        });
      }
      wx.hideLoading();
    });
  },
  vehicleSelect: function (e) {
    console.log(e)
    var dataList = this.data.dataList;
    for (var i = 0; i < dataList.length; i++) {
      dataList[i].checked = dataList[i].ID == e.detail.value;
      if (dataList[i].ID == e.detail.value) {
        wx.setStorage({
          key: "path_vehicle",
          data: dataList[i]
        });
        this.setData({
          selected: true
        })
      }
    }
    this.setData({
      dataList: dataList
    });
  },
  confirmData: function () {
    if (this.data.selected) {
      wx.navigateBack({
        delta: 1
      });
    } else {
      wx.showToast({
        title: "请选择车辆",
        image: "/images/wrong.svg",
        duration: 3000
      });
    }
  },
  cancelConfirmData: function () {
    wx.navigateBack({
      delta: 1
    });
  }
});